﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using Lin.Library.Web;
using System.Web.Security;
using System.Text;
using System.IO;

namespace Lin.Website.Admin
{
    public class BaseController : System.Web.UI.Page
    {
        protected string baseUrl = string.Empty;
        protected string fileUrl = string.Empty;

        protected override void OnInit(EventArgs e)
        {
            baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

            fileUrl = Request.Url.AbsolutePath;

            if (fileUrl.ToLower().IndexOf("login.aspx") == -1)
            {
                //身份认证，排除登陆页
                DoAuth();
            }

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            this.InvokeAndHandleException(() => base.OnLoad(e));
        }

        protected string ApiAdress(string key)
        {
            return baseUrl + ConfigurationManager.AppSettings[key];
        }

        protected void WriteJson(string json)
        {
            Response.Clear();
            Response.ContentType = WebContext.ContentType(WebContext.Content_Type.json);
            Response.Write(json);
            Response.End();
        }

        private void DoAuth()
        {
            if (!this.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
            }
            else
            {
                Response.Cache.SetNoStore();
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
        }

        private void InvokeAndHandleException(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                var html = new StringBuilder();
                var site = ex.StackTrace.Substring(ex.StackTrace.IndexOf("位置"), ex.StackTrace.IndexOf("行号"));

                site = site.Substring(site.LastIndexOf(@"\")+1, site.IndexOf(".cs"));

                html.Append("["+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"]\r\n");
                html.Append("错误信息：" + ex.Message+"\r\n");
                html.Append("错误方法：" + ex.TargetSite + "\r\n");
                html.Append("错误位置：" + site + "\r\n");

                if (!Directory.Exists(Server.MapPath("~/_Log/"))) {
                    Directory.CreateDirectory(Server.MapPath("~/_Log/"));
                }
                File.AppendAllText(Server.MapPath("~/_Log/"+DateTime.Now.ToString("yyyy-MM-dd")+".txt"),html.ToString());

                //IIS上不用?
                Server.Transfer("~/error.html");
            }
        }
    }
}